<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : Refunds.php
 * Created on : 2022-4-16 10:14:50
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\models;

use think\Model;
use haoteam\service\EasyWeChatService;

/**
 * 
 * Class Refunds
 * Tiger <1192851302@qq.com> 2022-4-16 10:14:50
 */
class Refunds extends Model {

    /**
     * 发起退款
     * @author Tiger <1192851302@qq.com>
     * @param type $out_trade_no
     * @param type $refund_money
     * @return boolean
     * @throws \think\Exception
     */
    public static function refund($out_trade_no, $refund_money = 0) {
        $payment = Payment::where('out_trade_no', $out_trade_no)->where('status', 1)->find();
        if (empty($payment)) {
            trace('退款时出现错误|' . $out_trade_no . '|' . $refund_money, 'error');
            throw new \think\Exception('支付订单不存在或未支付');
        }
        $refund_money = $refund_money ?: $payment['money'];
        $out_refund_no = date('YmdHis') . mt_rand(00000, 99999);
        self::create(['refund_trade_no' => $payment['out_trade_no'], 'refund_order_no' => $out_refund_no,
            'refund_money' => $refund_money]);
        //开始退款，不报错就是成功
        EasyWeChatService::refund($out_trade_no, $out_refund_no, $payment['money'], $refund_money);
        return true;
    }

}
